package org.jeecg.modules.door.stocket;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;

public class DoorServer {

    private static final int PORT = 8080;
    private static final int DEVICE_PORT = 8888; // 设备通信端口
    private static final ExecutorService executor = Executors.newCachedThreadPool();

    public static void main(String[] args) throws IOException {
        // 启动HTTP服务器
        new Thread(() -> {
            try {
                HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
                server.createContext("/queryToDevice", new QueryToDeviceHandler());
                server.setExecutor(executor);
                server.start();
                System.out.println("HTTP Server started on port " + PORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        // 启动TCP服务器
        new Thread(() -> {
            try (ServerSocket serverSocket = new ServerSocket(8888)) {
                System.out.println("TCP Server started on port " + 8888);
                while (true) {
                    Socket socket = serverSocket.accept();
                    executor.submit(() -> handleDeviceConnection(socket));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private static void handleDeviceConnection(Socket socket) {
        try (InputStream input = socket.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.US_ASCII))) {

            String message = reader.readLine();
            System.out.println("Received from device: " + message);
            // 这里可以添加处理设备上传数据的逻辑
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class QueryToDeviceHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String query = exchange.getRequestURI().getQuery();
            String[] params = query.split("&");
            String ip = null;
            for (String param : params) {
                if (param.startsWith("ip=")) {
                    ip = param.split("=")[1];
                    break;
                }
            }

            if (ip == null) {
                exchange.sendResponseHeaders(400, 0);
                exchange.getResponseBody().write("Invalid request".getBytes());
                return;
            }

            String hexQuery = "YOUR_HEX_QUERY_HERE"; // 替换为实际的16进制查询指令
            String deviceResponse = sendQueryToDevice(ip, hexQuery);

            exchange.sendResponseHeaders(200, deviceResponse.getBytes().length);
            OutputStream output = exchange.getResponseBody();
            output.write(deviceResponse.getBytes());
            output.close();
        }

        private String sendQueryToDevice(String ip, String hexQuery) {
            try (Socket socket = new Socket(ip, DEVICE_PORT);
                 OutputStream output = socket.getOutputStream();
                 PrintWriter writer = new PrintWriter(output, true)) {

                writer.println(hexQuery);

                // 假设设备会立即响应
                try (InputStream input = socket.getInputStream();
                     BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.US_ASCII))) {

                    String response = reader.readLine();
                    return response; // 返回设备的16进制响应
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error communicating with device";
            }
        }
    }
}